<!--
* description: 门店月计划提报
* author: wangml
* createdDate: 2020-12-01
-->

<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-api-style="apiStyle"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
      @hiddenColData="hiddenColData"
    />
    <sales-creation
      ref="carType"
      :popups-visible.sync="curPopupsVisible"
      :dialog-status="dialogStatus"
      :dynamic-edit-row-data="rowData"
      :popups-state="popstate"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/planReport'
import salesCreation from '../makeSalesPlan/salesCreation1'
import commData from '../common/index.js'
// import { requestRestful } from '@/api/commonRequest'

export default {
  name: 'ReportSalePlanOfStores',
  components: {
    OneTableTemplate,
    salesCreation
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      dialogStatus: 'stores',
      rowData: {},
      curPopupsVisible: false,
      genCodeFiled: null,
      selectList: [],
      clickRowsData: {},
      popstate: 'add',
      showdia: false,
      // 指定请求类型 可以统一在 utils/config.js中配置
      apiStyle: 'restful',
      dynamicApiConfig: api.storeMakeSalesPlan,
      refreshTableKey: '0',
      ruleSettingShow: false,
      // table表格查询API配置对象
      // 动态组件-查询条件
      tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
            : [
              ...commData.ModelOptions(2),
              {
                compKey: 'comKey6',
                labelName: '制定月份：',
                codeField: 'makingMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                format: 'yyyy-MM',
                dateOptionsType: '3',
                // type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'planMonthComp',
                labelName: '计划月份：',
                codeField: 'planMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                format: 'yyyy-MM',
                startTime: '',
                dateOptionsType: '3',
                // parentFileds: 'disabled:makingMonth-planMonth--false',
                // disabled: true,
                // type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey9',
                labelName: '制作人：',
                codeField: 'creator',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey10',
                labelName: '优先级别：',
                codeField: 'priorityLevel',
                lookuptype: 'VE1227',
                component: () => import('@/components/org/commonSelect'),
                type: 'inputText',
                isMul: true,
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey11',
                labelName: '计划状态：',
                codeField: 'planStatus',
                component: () => import('@/components/org/commonSelect'),
                customObj: { listQuery: { lookupTypeCode: 'VE1112', attribute3: '1' }},
                type: 'dropdownList',
                isMul: true,
                isMust: false,
                span: 6
              },
              {
                compKey: 'compKey12',
                labelName: '制作时间：',
                codeField: 'startTime,endTime',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'daterange',
                isMul: false,
                isMust: false
              }

            ],
      formField: {
        planMonth: '',
        makingMonth: '',
        creator: '',
        priorityLevel: '',
        planStatus: '',
        startTime: '',
        endTime: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: ''
      },
      // 动态组件-按钮
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'comKey1',
            type: 'primary',
            size: 'small',
            name: 'search',
            position: 'right',
            clickEvent: () => this.queryTable(),
            text: '查询'
          },
          {
            compKey: 'comKey0',
            type: '',
            size: 'small',
            name: 'reset',
            position: 'right',
            clickEvent: () => this.reset(),
            text: '重置'
          },
          {
            compKey: 'comKey2',
            type: '',
            size: 'small',
            name: 'newOrder',
            position: 'left',
            clickEvent: () => this.add(),
            text: '计划制定'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: '',
            position: 'left',
            clickEvent: () => this.delData(),
            text: '删除',
            disabled: true
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: 'submissionUp',
            position: 'left',
            clickEvent: () => this.submit(),
            text: '提交',
            disabled: true
          }

        ],
      // 动态组件-表格网格列
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            label: '操作',
            minWidth: 180,
            fixed: true,
            isComponent: true,
            comps: [
              {
                compKey: 'propKey1',
                labelName: '编辑',
                component: () => import('@/components/org/linkButton'),
                // component: () => import('@/components/org/datePicker/datePicker.vue'),
                rowFileds: 'show:planStatusCode-未提交|门店驳回',
                clickEvent: (index) => this.edit(index)
              }
            ]
          },
          {
            prop: 'planStatusCode',
            label: '计划状态'
          },
          {
            prop: 'makingMonth',
            label: '制定月份'
          },
          {
            prop: 'ttCode',
            label: '22位码',
            width: 175
          },
          {
            prop: 'planMonth',
            label: '计划月份',
            width: 120
          },
          {
            prop: 'planWeek',
            label: '计划周度'
          },
          {
            prop: 'planNum',
            label: '计划数量'
          },
          {
            prop: 'carSeriesCn',
            label: '车系编码'
          },
          {
            prop: 'carSeriesCode',
            label: '车系名称'
          },
          {
            prop: 'carConfigCode',
            label: '基础车型编码'
          },
          {
            prop: 'carConfigCn',
            label: '基础车型名称',
            width: 110
          },
          // {
          //   prop: 'VehicleConfigurationCode',
          //   label: '车型配置编码'
          // },
          {
            prop: 'optionalPagCode',
            label: '选装包编码'
          },
          {
            prop: 'optionalPagName',
            label: '选装包名称'
          },
          {
            prop: 'carColorCode',
            label: '车身颜色编码'
          },
          {
            prop: 'carColorName',
            label: '车身颜色名称'
          },
          {
            prop: 'carIncolorCode',
            label: '内饰颜色编码'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色名称'
          },
          {
            prop: 'creator',
            label: '制作人'
          },
          {
            prop: 'createdDate',
            label: '制作时间',
            width: 120
          },
          {
            prop: 'submitTime',
            label: '提交时间'
          },
          {
            prop: 'empName',
            label: '审核人'
          },
          {
            prop: 'auditTime',
            label: '审核时间'
          },
          {
            prop: 'rejectNote',
            label: '驳回原因'
          },
          {
            prop: 'priorityLevel',
            label: '优先级别'
          }
        ],
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList = selection.map((item) => {
            return item.updateControlId
          })
          this.monthPlanId = selection.map((item) => {
            return item.monthPlanId
          })
          this.planStatus = selection.map((item) => {
            return item.planStatus
          })
          this.selectionList = selection
          this.list = this.selectionList.reduce((pre, cur) => {
            pre.push({ monthPlanId: cur.monthPlanId,
              updateControlId: cur.updateControlId,
              planStatus: cur.planStatus,
              planMonth: cur.planMonth,
              planWeek: cur.planWeek,
              carSerId: cur.carSerId,
              carConfigId: cur.carConfigId,
              carOptionalpagId: cur.carOptionalpagId,
              carColorId: cur.carColorId,
              carIncolorId: cur.carIncolorId,
              ttCode: cur.ttCode,
              planNum: cur.planNum
            })
            return pre
          }, [])
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  watch: {
    'formField.makingMonth': {
      handler(val) {
        if (!val) {
          this.formField.planMonth = ''
        } else {
          // 有值 动态设置时间禁用
          this.tableComponents.filter(item => item.compKey === 'planMonthComp')[0].startTime = val
        }
      }
    },
    'formField': {
      handler(form) {
        if (form.makingMonth !== '') {
          if (new Date(form.planMonth) <= new Date(form.makingMonth)) {
            this.$message('计划月份大于制定月份，请重新选择!')
            this.formField.planMonth = ''
            const comp = this.$refs['multipleTable'].$refs['planMonthComp'][0]
            comp.modelCode = ''
            comp.$children[0].$children[0].$children[0].focus()
          }
        }
        // !form.makingMonth ? this.formField.planMonth = '' : ''
      },
      deep: true
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },
  methods: {

    handle() { },
    add() {
      this.dialogStatus = 'stores'
      this.popstate = 'add'
      this.curPopupsVisible = true
    },
    // 提交
    submit() {
      this.$requestAPI({
        apiUrl: api.storeSalesSend.APIUrl,
        variables: {
          updateControlIds: this.selectList,
          monthPlanIds: this.monthPlanId,
          planStatus: this.planStatus
        }
      }).then(res => {
        if (res.result === '1') {
          this.$message(res.msg ? res.msg : '计划发送成功!')
          this.$refs['multipleTable'].queryTable(1)
        } else {
          this.$confirm(res.msg, '提示', {
            type: 'warning'
          })
        }
      }).catch(err => {
        console.info(err)
      })
    },
    // 自动生成codeField
    genUtil: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
    // 保存 或新增 后会调用此方法
    popClose(type) {
      this.showdia = false
      if (type === 1) {
        this.queryTable(1)
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        if (isCheck) {
          const del = selection.every((item) => {
            return item.planStatus === '7' || item.planStatus === '4'
          })
          if (del) {
            btns[0].disabled = !del
          } else {
            btns[0].disabled = true
          }
          const submit = selection.every((item) => {
            return item.planStatus === '7' || item.planStatus === '4'
          })
          if (submit) {
            btns[1].disabled = !submit
          } else {
            btns[1].disabled = true
          }
        } else {
          btns[0].disabled = true
        }
        // btns.forEach((item) => {
        //   item.disabled = !isCheck
        // })
      }
    },

    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    },
    edit(idx) {
      const data = this.$utils.deepCopy(this.$refs.multipleTable.list[idx])
      switch (data.priorityLevel) {
        case '高':
          data.priorityLevel = '1'
          break
        case '中':
          data.priorityLevel = '2'
          break
        case '低':
          data.priorityLevel = '3'
          break
      }
      this.rowData = data
      this.popstate = 'edit'
      this.dialogStatus = 'storesEdit'
      this.curPopupsVisible = true
    },
    selectRowsData(rowdata) {

    },

    // 查看附件
    checkFile(index, type) {
      // location.href = process.env.VUE_APP_BASE_API + this.$refs['multipleTable'].list[index].downloadUrl
      window.open(this.$refs['multipleTable'].list[index][type])
    },

    // 删除按钮单条删除
    delOneData(row) {
      const data = [this.$refs['multipleTable'].list[row]]
      this.delData(data)
    },

    // 数据批量删除
    delSeleteData() {
      const data = this.$refs['multipleTable'].$refs['multipleTable'].selection
      this.delData(data)
    },

    // 删除
    delData(selectData) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$requestAPI({
          apiUrl: api.delStoreMonthPlan.APIUrl,
          variables: { updateControlId: this.selectList, monthPlanId: this.monthPlanId, planStatus: this.planStatus }
        }).then(res => {
          if (res.result === '1') {
            this.$message(res.msg ? res.msg : '删除成功')
            this.queryTable(1)
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

